package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC870 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int[] advantageCount(int[] A, int[] B) {
            TreeMap<Integer, List<Integer>> aMap = new TreeMap<>();
            TreeMap<Integer, List<Integer>> bMap = new TreeMap<>(Collections.reverseOrder());
            for (int i = 0; i < A.length; i++) {
                int num = A[i];
                if (!aMap.containsKey(num)) {
                    List<Integer> idxList = new LinkedList<>();
                    aMap.put(num, idxList);
                }
                aMap.get(num).add(i);
            }

            for (int i = 0; i < B.length; i++) {
                int num = B[i];
                if (!bMap.containsKey(num)) {
                    List<Integer> idxList = new LinkedList<>();
                    bMap.put(num, idxList);
                }
                bMap.get(num).add(i);
            }

            int[] res = new int[A.length];
            for (Integer bnum : bMap.keySet()) {
                for (Integer bIdx : bMap.get(bnum)) {
                    Integer anum = aMap.ceilingKey(bnum + 1);
                    if (null == anum) {
                        // no num is bigger than bnum, so just use the smallest
                        int aSmallerNum = aMap.firstEntry().getKey();
                        res[bIdx] = aSmallerNum;
                        if (aMap.get(aSmallerNum).size() <= 1) aMap.remove(aSmallerNum);
                        else aMap.get(aSmallerNum).remove(0);
                    } else {
                        res[bIdx] = anum;
                        if (aMap.get(anum).size() <= 1) aMap.remove(anum);
                        else aMap.get(anum).remove(0);
                    }
                }
            }

            return res;
        }
    }

    public void run() {
        Solution solution = new Solution();
//        A = [2,7,11,15], B = [1,10,4,11]
//        A = [12,24,8,32], B = [13,25,32,11]
        int[] arr1 = InputUtil.toIntegerArray("[12,24,8,32]");
        int[] arr2 = InputUtil.toIntegerArray("[13,25,32,11]");
        System.out.println(Arrays.toString(solution.advantageCount(arr1, arr2)));
    }

    public static void main(String[] args) throws Exception {
        LC870 an = new LC870();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
